const express = require('express')
const app = express()
const log4 = require('../tools/logs')
const uuidv1 = require('uuid/v1')
const request = require('request')
const config = require('../config/config')
const mdbs = require('../models/mongodbs')
const sql_dbs = require('../models/dbs')
// 时间戳产生函数  
var createTimeStamp = () => {
    return parseInt(new Date().getTime() / 1000) + ''
}
exports.astokenOpid = (req, res) => {
    var CODES = req.body.code
    log4.logs(CODES)
    var appids = 'wxe95ab88d002a714e'
    var secretID =  '244a70f73a4388aa2e4988ddaa3ca0b6'
    var resUrl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='+appids+'&secret='+secretID+'&code=' + CODES + '&grant_type=authorization_code'
    request.get(resUrl,function(error,response,body){
        if(!error){
            log4.logs(response.body)
            res.json({
                code:200,
                msg:'访问成功',
                data:response.body
            })
        }else{
            log4.logs(error)
            res.json({
                code:201,
                msg:'访问失败',
                data:error
            })
        }
    })  
}
exports.getPayurl = (req,res)=>{
    var APPID = 'wxe95ab88d002a714e'
    var URLS = 'http://www.ubitcar.com/app/'
    var urled = 'https://open.weixin.qq.com/connect/oauth2/authorize?'
    var canshu = 'appid='+APPID+'&redirect_uri=' + encodeURIComponent(URLS) + '&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect'
    var lasturl = urled+canshu
    console.log(lasturl)
}
exports.loginFunc = (req,res)=>{
    let username = req.body.username
    let pawword = req.body.pawword
    if(username == 'admin'){
        
    }else{
        res.json({
            code:201,
            msg:'用户名错误'
        })
        return
    }
    if(pawword == 'zzc_ubitcar'){
        res.json({
            code:200,
            msg:'登陆成功',
            data:{
                token:'aNsiafjjln1f0'
            }
        })
    }else{
        res.json({
            code:201,
            msg:'密码错误'
        })
    }
}
//支付成功回调方法
exports.wxPayNotice = function(req,res){
    let noticexml = req.body
    log4.logs('打印支付成功回调')
    log4.logs(noticexml.xml)
    let NoticeResult = noticexml.xml
    let searchJson = { 'transaction_id':NoticeResult.transaction_id }
    let jsoned = {
        attach:NoticeResult.attach,
        bank_type:NoticeResult.bank_type,
        cash_fee:NoticeResult.cash_fee,
        fee_type:NoticeResult.fee_type,
        is_subscribe:NoticeResult.is_subscribe,
        mch_id:NoticeResult.mch_id,
        nonce_str:NoticeResult.nonce_str,
        openid:NoticeResult.openid,
        out_trade_no:NoticeResult.out_trade_no,
        result_code:NoticeResult.result_code,
        return_code:NoticeResult.return_code,
        sign:NoticeResult.sign,
        time_end:NoticeResult.time_end,
        total_fee:NoticeResult.total_fee,
        trade_type:NoticeResult.trade_type,
        transaction_id:NoticeResult.transaction_id
    }
    mdbs.finded('wxpay_list_tables',searchJson,function(err,result){
        if(result == '' || result == null){
            
            mdbs.insertOne('wxpay_list_tables',jsoned,function(errs,result){
                if(errs){
                    log4.logs('数据库插入失败'+errs)
                    log4.logs('transaction_id'+NoticeResult.transaction_id)
                }else{
                    log4.logs('数据库插入成功')
                    log4.logs('transaction_id'+NoticeResult.transaction_id)
                }
            })
        }else{
            return false
        }
    })
}
exports.getWxpayList = function(req,res,next){
    let pageNow = 1
    let wxOrder = ''
    try{
        pageNow = req.query.pageNow
        wxOrder = req.query.wxOrder
    }catch(err){
        log4.logs('参数错误')
    }
    let searchJson = {}
    if(wxOrder == null || wxOrder == '' || wxOrder == 'undefined'){
        searchJson = {}
    }else{
        searchJson = {
            "transaction_id":wxOrder
        }
    } 
    mdbs.find('wxpay_list_tables',searchJson,{"time_end":-1},pageNow,function(err,result){
        if(err){
            log4.logs('查询失败')
            res.json({
                code:201,
                msg:'查询失败'
            })
        }else{
            res.json({
                code:200,
                data:result
            })
            return result
        }
    })
}

exports.getPageNum = function(req,res){
    let counted = 11
     mdbs.getAllCount('wxpay_list_tables',function(num){
        counted = num
        res.json({
            code:200,
            pageNum:counted
        })
    })
}
exports.getPageNumUser = function(req,res){
    let counted = 11
     mdbs.getAllCount('wxpay_user_table',function(num){
        counted = num
        res.json({
            code:200,
            pageNum:counted
        })
    })
}
let countFee = (invitation,slot)=>{
    if(slot == 1){
        //没有折扣
        return 600*invitation
    }else if(slot == 3){
        //一个季度
        return 1600*invitation
    }else if(slot == 12){
        //一年
        return 5000*invitation
    }else{
        return false
    }
}
exports.getUserNum = function(req,res){
    //入参邮箱和时间段
    let emils = ''
    let timeSlot = ''
    const reqUrl = 'http://www.ubitcar.com/invitecount'
    try{
        emils = req.body.emil_s
        timeSlot = req.body.slot
        const reg = new RegExp('"',"g");  
        emils = emils.replace(reg, ""); 
    }catch(err){
        log4.logs(err)
    }
     
    let reqData = {'email':emils}
    let money = ''
    request.post({url:reqUrl, formData: reqData}, function optionalCallback(err, httpResponse, body) {
        if (err) {
          return console.error('upload failed:', err);
        }
        let in_result = JSON.parse(body).count
        if(in_result == null || in_result == 0 || in_result < 5){
            money = countFee(1,timeSlot)
        }else{
            money = countFee(0.5,timeSlot)
        }
        res.json({
            code:200,
            data:{
              feee:money,
              invitation:in_result
          }
        })
      })
}
function countEndtime(maxviptime,slot){
    return parseInt(maxviptime) + 24*60*60*1000* parseInt(slot)*30
}
exports.getPayParameter = async function(req,res){
    let payInfo = {
        fee:'',
        slot:'',
        email:'',
        openid:'',
        vipbegintime:'',
        vipendtime:'',
        isvip:'true',
        paytime:new Date(),
        timestamp:new Date().getTime(),
        endtimetamp:''
    }
    try{
        payInfo.fee = req.body.money
        payInfo.slot = req.body.slot
        payInfo.email = req.body.emil
        payInfo.openid = req.body.openid

    }catch(err){
        log4.logs(err)
    }
    var d = new Date()
    var startMonth = d.getMonth()+1
    payInfo.vipbegintime = d.getFullYear()+'-'+startMonth+'-'+d.getDate()
    if(payInfo.slot == 1){
        d.setMonth(d.getMonth()+1)
    }else if(payInfo.slot == 3){
        d.setMonth(d.getMonth()+3)
    }else if(payInfo.slot == 12){
        d.setMonth(d.getMonth()+12)
    }else{
        log4.logs('日期时间报错')
    }
    var endMonth = d.getMonth()+1
    payInfo.vipendtime = d.getFullYear()+'-'+endMonth+'-'+d.getDate()
    payInfo.endtimetamp = d.getTime()

    await mdbs.finded('wxpay_isvip_table',{'email':payInfo.email},async function(err,results){
        let maxviptime = ''
        if(!err){
            if(results == ''){
                mdbs.insertOne('wxpay_isvip_table',payInfo,function(errs,result){
                    if(errs){
                        log4.logs('数据库插入失败'+errs)
                    }else{
                        log4.logs('数据库插入成功')
                    }
                })
            }else{
                await results.forEach(itemed=>{
                    if(itemed.endtimetamp >= maxviptime){ 
                        maxviptime = itemed.endtimetamp
                    }
                })
                await mdbs.updateMany('wxpay_isvip_table',{'email':payInfo.email},{'endtimetamp':countEndtime(maxviptime,payInfo.slot)},function(err,result){
                    if(!err){
                        log4.logs('isvip表插入成功')
                    }
                })
            }
        }
    })
    await mdbs.insertOne('wxpay_user_table',payInfo,function(errs,result){
        if(errs){
            log4.logs('数据库插入失败'+errs)
        }else{
            log4.logs('数据库插入成功11')
        }
    })

    res.send('插入数据库')
}
exports.getUserPayList = function(req,res){

    let pageNow = 1
    let email_form = ''
    try{
        pageNow = req.query.pageNows
        email_form = req.query.email_form
    }catch(err){
        log4.logs('参数错误')
    }
    let searchJson = {}
    if(email_form == null || email_form == '' || email_form == 'undefined'){
        searchJson = {}
    }else{
        searchJson = {
            "email":email_form
        }
    } 
    mdbs.find('wxpay_user_table',searchJson,{"timestamp":-1},pageNow,function(err,result){
        if(err){
            log4.logs('数据库查询失败'+err)
            res.json({
                code:201,
                msg:'查询失败'
            })
        }else{
            log4.logs(result)
            res.json({
                code:200,
                data:result
            })
        }
    })
}
exports.ismember = function(req,res){
    let reqemail = ''
    try{
        reqemail = req.body.email
    }catch(error){
        log4.logs(error)
    }
    let searchData = {
        email:reqemail
    }
    let d = new Date()
    let nowTime = d.getFullYear()+''+d.getMonth()+''+d.getDate()
    let isvip = false
    mdbs.finded('wxpay_user_table',searchData,function(err,result){
        if(err){
            res.json({
                code:201,
                msg:'未知错误'
            })
        }else{
           result.forEach(item => {
             if(item.vipendtime >= nowTime){
                isvip = true
                return;
             }else{
                isvip = false
             }  
           })
        }
        res.json({
            code:200,
            data:{
                isvips:isvip
            }
        })
    })
}
exports.isVipFunc = function(req,res){
    let reqemail = ''
    try{
        reqemail = req.body.userEmail
    }catch(err){
        log4.logs(err)
    }
    if(reqemail=='1075888691@qq.com' || reqemail=='8682069@qq.com' || reqemail=='wuxiaotan@126.com' || reqemail=='rhy52671@cjpeg.com'){
        res.json({
            code:200,
            msg:'接口访问成功',
            data:{
                isvip:true
            }
        })
        return;
    }
    let searchData = {
        email:reqemail
    }
    var nowTime = new Date().getTime()   
    //var nowTime = '1540823458000'
    var isvipGloble = ''
    mdbs.finded('wxpay_isvip_table',searchData,function(err,result){
        if(err){
            res.json({
                code:201,
                msg:'未知错误'
            })
        }else{
           result.forEach(item=>{
                if(parseInt(item.endtimetamp) - parseInt(nowTime) >= 0){
                    isvipGloble = true
                    return;
                }else{
                    isvipGloble = false
                }
           })
        }
        res.json({
            code:200,
            msg:'接口访问成功',
            data:{
                isvip:isvipGloble
            }
        })
    })
}
exports.failmsg = function(req,res){
    let noticexml = req.body
    log4.logs('打印支付失败原因')
    log4.logs(noticexml)
    console.log('---------------------------------------------')
    console.log(req.body.notice)
    res.send('fail')
}